package cn.dansj.handler.tasks;

import cn.dansj.annotation.MarkAsTask;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.common.request.RestTemplateUtils;
import cn.dansj.common.redis.RedisUtils;
import cn.dansj.common.utils.transfer.*;
import cn.dansj.common.context.ApplicationContextProvider;
import com.xxl.job.handler.Job;
import org.htmlunit.BrowserVersion;
import org.htmlunit.NicelyResynchronizingAjaxController;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@MarkAsTask(id = 2)
public class GetLotteryInfo extends Job {
    private static final String selectCountSql = "select count(1) cnt from t_caipiao_info where code=? and qs=?";
    private static final String insertSql = "insert  into t_caipiao_info(sequence,code,open_code,name,qs,open_time) values(?,?,?,?,?,?)";
    private static final String deleteSql = "delete from t_caipiao_info where code=? and qs=?";

    @Override
    public void execute() {
        //获取超级大乐透和七星彩数据
        List<String> codeList = ArrayUtils.asList("ssq", "cjdlt", "qlc", "qxc", "fc3d");

        for (String code : codeList) {
            String url = "https://www.mxnzp.com/api/lottery/common/latest?code=" + code + "&size=50&app_id=chretnsinicmefmj&app_secret=BN0fxR6f8buGw5OykrlOiUm6Rv2ywNcF";
            Map<?, ?> request = DictMap.parseObject(RestTemplateUtils.defaultInstance().get(url, Map.class).get("data"), Map.class);
            logger.info(DictMap.toJSONString(request));
            if (Verification.checkNull(request)) continue;

            try {
                Thread.sleep(1200);
                int del = jdbcTemplate.update(deleteSql, code, request.get("expect"));
                logger.info("清除历史开奖记录({}):code:{},qs:{}", del, code, request.get("expect"));
                int newRecord = jdbcTemplate.update(insertSql, RandomUtils.sequence(), code, request.get("openCode"), request.get("name"), request.get("expect"), request.get("time"));
                logger.info("{} qs:{} 开奖记录新增{}条", request.get("name"), request.get("expect"), newRecord);
            } catch (InterruptedException ignore) {
            }
        }

        //从官网抓取双色球，福彩，七乐彩数据

        // 创建一个WebClient实例，相当于一个浏览器
        final BrowserVersion browser = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.CHROME).setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();
        try (WebClient webClient = new WebClient(browser)) {
            webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
            // webClient.getOptions().setActiveXNative(false);
            webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
            webClient.getOptions().setJavaScriptEnabled(true); //很重要，启用JS
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX

            // 打开网页
            HtmlPage page = webClient.getPage("https://www.cwl.gov.cn/ygkj/kjgg/");
            final Element element = Jsoup.parse(page.asXml()).getElementsByClass("ygkj_kjgg").get(0).firstElementChild();
            if (element == null) {
                logger.error("未获取到彩票数据\n{}", page);
                return;
            }

            final String ssqCode = element.selectFirst(".ssqRed-dom").text().replaceAll("[\\[\\]]", "") + "+" + element.selectFirst(".ssqBlue-dom").text().replaceAll("[\\[\\]]", "");
            final String ssqQh = element.selectFirst(".ssqQh-dom").text();

            int cnt = Integer.parseInt(String.valueOf(jdbcTemplate.queryForMap(selectCountSql, "ssq", ssqQh).get("cnt")));
            if (cnt == 0) {
                int newRecord = jdbcTemplate.update(insertSql, RandomUtils.sequence(), "ssq", ssqCode, "双色球", ssqQh, DateTime.getInstance().setTime(21, 15, 0, 0));
                logger.info("双色球开奖记录新增{}条", newRecord);
            }

            final String fcCode = element.selectFirst(".fcBlue-dom").text().replaceAll("[\\[\\]]", "");
            final String fcQh = element.selectFirst(".fcQh-dom").text();

            cnt = Integer.parseInt(String.valueOf(jdbcTemplate.queryForMap(selectCountSql, "fc3d", fcQh).get("cnt")));
            if (cnt == 0) {
                int newRecord = jdbcTemplate.update(insertSql, RandomUtils.sequence(), "fc3d", fcCode, "福彩3D", fcQh, DateTime.getInstance().setTime(21, 15, 0, 0));
                logger.info("福彩3D开奖记录新增{}条", newRecord);
            }

            final String qlcCode = element.selectFirst(".qclRed-dom").text().replaceAll("[\\[\\]]", "") + "+" + element.selectFirst(".qclBlue-dom").text().replaceAll("[\\[\\]]", "");
            final String qlcQh = element.selectFirst(".qlcQh-dom").text();

            cnt = Integer.parseInt(String.valueOf(jdbcTemplate.queryForMap(selectCountSql, "qlc", qlcQh).get("cnt")));
            if (cnt == 0) {
                int newRecord = jdbcTemplate.update(insertSql, RandomUtils.sequence(), "qlc", qlcCode, "七乐彩", qlcQh, DateTime.getInstance().setTime(21, 15, 0, 0));
                logger.info("七乐彩开奖记录新增{}条", newRecord);
            }
        } catch (Exception e) {
            logger.error(e);
        }

        final RedisUtils redisUtils = ApplicationContextProvider.getBean(RedisUtils.class);
        final List<String> keys = redisUtils.keys("InterfaceResult@*");
        List<String> removeCache = new ArrayList<>();
        for (String name : keys) {
            final Object url = redisUtils.hget(name, "url");
            if ("/caipiao".equals(url)) {
                removeCache.add(name);
            }
        }

        final Long delete = redisUtils.delete(removeCache);

        logger.info("删除缓存{}条", delete);
    }
}
